package com.example.androidproject.movie.activity;

import androidx.annotation.NonNull;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.androidproject.R;
import com.example.androidproject.myview.MyVideoView;
import com.example.androidproject.movie.bean.ResultBeanData;
import com.example.androidproject.utils.ScreenNoOperationTiming;

import java.util.Timer;
import java.util.TimerTask;

public class MoviePlayActivity extends Activity {
    private final String TAG = "GGSTUDY";
    private ResultBeanData.DataBean data;
    private Button paly_btn;
    private MyVideoView movie_video;
    private LinearLayout ll_movie_loding, ll_movie_control, lv_movie_toward_left_15s, lv_movie_star, lv_movie_toward_rigth_15s, lv_movie_full_screen;
    private TextView tv_movie_loding;
    private ImageView iv_movie_toward_left_15s, iv_movie_star, iv_movie_toward_rigth_15s, iv_movie_full_screen;
    private boolean frist_pass = true;
    public ScreenNoOperationTiming screenNoOperationTiming;
    private FrameLayout fl_movie_video;
    private RelativeLayout rl_movie_play;
    private boolean isFullScreen = false;

    //
    private MediaController mc;
    private SurfaceView movie_surfaceView;
    private MediaPlayer mediaPlayer;
    private PowerManager.WakeLock mWakeLock;
    private ProgressBar mProgress;

    @SuppressLint("InvalidWakeLockTag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie_play);
        //设置顶部状态栏为透明
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

        initView();
        initPage();
        clickListener();

        /**
         * 屏幕锁定  这里有问题后续解决
         */
        // 保持屏幕高亮
//        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        //mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "Test");
    }


    /**
     * 播放状态 枚举
     */
    private enum PLAYER_STATUS {
        IDLE, PREPARING, PAUSED, PREPARED, RESUMED, STOPPED
    }

    /**
     * 当前播放状态
     */
    public PLAYER_STATUS mPlayerStatus = PLAYER_STATUS.IDLE;
    /**
     * 事件标志
     */
    private int mLastPos;

    //开始播放
    public void startPlay() {
        if (null != mWakeLock && (!mWakeLock.isHeld())) {
            mWakeLock.acquire();
        }
        if (null != movie_video) {
            movie_video.start();
            mPlayerStatus = PLAYER_STATUS.PREPARING;
        }
    }

    /**
     * 暂停播放
     */
    public void pause() {
        if (null != mWakeLock) {
            mWakeLock.release();
        }
        if (null != movie_video && movie_video.isPlaying()) {
            movie_video.pause();
            mPlayerStatus = PLAYER_STATUS.PAUSED;
            mLastPos = getCurrentTime();
        }
    }

    /**
     * 继续播放
     */
    public void resume() {
        if (null != mWakeLock) {
            mWakeLock.acquire();
        }
        if (null != movie_video) {
            movie_video.start();
            mPlayerStatus = PLAYER_STATUS.RESUMED;
        }
    }

    /**
     * 停止播放
     */
    public void stop() {

        if (null != mWakeLock) {
            mWakeLock.release();
        }
        if (null != movie_video) {
            mLastPos = getCurrentTime();
            movie_video.stopPlayback();
            mPlayerStatus = PLAYER_STATUS.STOPPED;
        }
    }

    /**
     * 判断是否正在播放
     *
     * @return
     */
    public boolean isPlaying() {
        return movie_video != null && movie_video.isPlaying();
    }

    /**
     * 是否暂停
     */
    public boolean isPause() {
        return mPlayerStatus == PLAYER_STATUS.PAUSED;
    }

    /**
     * 释放资源
     */
    public void release() {
        if (null != mWakeLock) {
            mWakeLock.release();
            mWakeLock = null;
        }
        if (null != movie_video) {
            movie_video.stopPlayback();
            movie_video = null;
        }
    }

    //获取视频总时间
    public int getTotalTime() {
        return movie_video == null ? 0 : movie_video.getDuration();
    }

    //获取视频当前时间
    public int getCurrentTime() {
        return movie_video == null ? 0 : movie_video.getCurrentPosition();
    }


    /**
     * 初始化控件
     */
    private void initView() {
        paly_btn = findViewById(R.id.movie_playBtn);
        //movie_surfaceView = findViewById(R.id.movie_surfaceView);
        movie_video = findViewById(R.id.movie_video);
        ll_movie_loding = findViewById(R.id.ll_movie_loding);
        tv_movie_loding = findViewById(R.id.tv_movie_loding);
        ll_movie_control = findViewById(R.id.ll_movie_control);
        iv_movie_toward_left_15s = findViewById(R.id.iv_movie_toward_left_15s);
        iv_movie_star = findViewById(R.id.iv_movie_star);
        iv_movie_toward_rigth_15s = findViewById(R.id.iv_movie_toward_rigth_15s);
        iv_movie_full_screen = findViewById(R.id.iv_movie_full_screen);
//        fl_movie_video = findViewById(R.id.fl_movie_video);
        rl_movie_play = findViewById(R.id.rl_movie_play);
        //ll_movie_control.setBackgroundColor(Color.TRANSPARENT);
        lv_movie_toward_left_15s = findViewById(R.id.lv_movie_toward_left_15s);
        lv_movie_star = findViewById(R.id.lv_movie_star);
        lv_movie_toward_rigth_15s = findViewById(R.id.lv_movie_toward_rigth_15s);
        lv_movie_full_screen = findViewById(R.id.lv_movie_full_screen);
    }

    /**
     * 初始化页面
     */
    @SuppressLint("ClickableViewAccessibility")
    private void initPage() {
        Intent intent = getIntent();
        data = intent.getParcelableExtra("data");
        movie_video.setVideoPath(data.getM3u8());
        movie_video.start();
        movie_video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                // 这里可以解决视频加载完成前的黑屏问题
                mp.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {
                        if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                            ll_movie_loding.setVisibility(View.GONE);
                            tv_movie_loding.setVisibility(View.GONE);
                            movie_video.setBackgroundColor(Color.TRANSPARENT);
                            iv_movie_star.setBackgroundResource(R.drawable.pause);
                            Log.d(TAG, "onInfo: 加载完成");
                        }
                        return true;
                    }
                });
                // 将控制条添加到视频下方
                mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
                    @Override
                    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                        /**
                         * 这里是可以监听 视频大小变化的
                         */
                        //mc = new MediaController(MoviePlayActivity.this);
                        //movie_video.setMediaController(mc);
                        //mc.setAnchorView(movie_video);
                        //RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 60);// 创建参数对象，设置宽和高
                        //layoutParams.setMargins(0, height, 0, 0);
                        //ll_movie_control.setLayoutParams(layoutParams);
                    }
                });
            }
        });
        movie_video.setOnTouchListener(new View.OnTouchListener() {
            /**
             * 屏幕三秒不动 就隐藏控制条
             */
            public MyTimerTask myTimerTask;
            public Timer mtimer;

            /**
             * 计时任务管理
             */
            class MyTimerTask extends TimerTask {
                @Override
                public void run() {
                    if (System.currentTimeMillis() - screenNoOperationTiming.mLastActionTime > 1000 * 3 * 1) {
                        screenNoOperationTiming.stopTimer();
                        // 在主线程中修改
                        MoviePlayActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ll_movie_control.setVisibility(View.GONE);
                                frist_pass = true;
                            }
                        });
                    }
                }
            }

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                /**
                 * 屏幕点击 隐藏或显示控制条
                 */
                if (frist_pass) {
                    /**
                     * 屏幕三秒不动 就隐藏控制条
                     */
                    myTimerTask = new MyTimerTask();
                    mtimer = new Timer();
                    screenNoOperationTiming = new ScreenNoOperationTiming(mtimer);
                    screenNoOperationTiming.startTimer();
                    screenNoOperationTiming.mtimer.schedule(myTimerTask, 0, 1000);
                    //
                    ll_movie_control.setVisibility(View.VISIBLE);
                    frist_pass = false;
                } else {
                    ll_movie_control.setVisibility(View.GONE);
                    frist_pass = true;
                }

                return false;
            }
        });
    }

    /**
     * 横屏
     */
    public void FullScrenn() {
        isFullScreen = true;
        // 把当前的 activity最外层的布局最大化
        rl_movie_play.setLayoutParams(new FrameLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 横屏
        /**
         * 这里有个不解之处就是 这句代码不运行 video的视频大小在 横屏 竖屏 的时候就不会匹配videoview的大小 运行了就可以了
         */
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//常亮
        //设置窗体全屏，进行全屏显示。否则横屏时，会出现状态栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置videoView全屏播放
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
    }

    /**
     * 竖屏
     */
    public void VerticalScreen() {
        isFullScreen = false;
        rl_movie_play.setLayoutParams(new FrameLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, 600));
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);//竖屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//常亮

    }

    /**
     * 点击事件监听
     */
    private void clickListener() {
        lv_movie_star.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPlaying()) {
                    pause();
                    iv_movie_star.setBackgroundResource(R.drawable.start16);
                } else {
                    resume();
                    iv_movie_star.setBackgroundResource(R.drawable.pause);
                }

            }
        });

        lv_movie_full_screen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isFullScreen) {
                    FullScrenn();
                    iv_movie_full_screen.setBackgroundResource(R.drawable.narrow_screen_white_16);
                } else {
                    iv_movie_full_screen.setBackgroundResource(R.drawable.full_screen_white16);
                    VerticalScreen();
                }

            }
        });
    }

    /**
     * 横屏竖屏 监听
     *
     * @param newConfig
     */
    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 如果是橫屏時候
        try {
            // Checks the orientation of the screen
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                Log.d(TAG, "onConfigurationChanged: 我横屏了");
            } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                Log.d(TAG, "onConfigurationChanged: 我竖屏了");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 监听返回键
     */
    @Override
    public void onBackPressed() {
        if (isFullScreen) {
            VerticalScreen();
            return;
        } else {
            super.onBackPressed();
        }
    }
}

